package com.excalibur.core.util.web;

import com.excalibur.core.util.json.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by tianbenzhen on 2016/7/11.
 */
public class AjaxResponseUtil {

    private final static Logger logger = LoggerFactory.getLogger(AjaxResponseUtil.class);

    public static void outJsonp(HttpServletRequest request, HttpServletResponse response, Object object) {
        String callback = request.getParameter("callback");
        String string = JsonUtils.objectToJson(object);
        if (callback != null && callback.length() > 0) {
            response.setContentType("text/javascript;charset=UTF-8");
            string = (new StringBuilder()).append(callback).append("(").append(string).append(")").toString();
        } else {
            response.setContentType("text/plain;charset=UTF-8");
        }
        out(response, string);
    }

    public static void outJsonJsonp(HttpServletRequest request, HttpServletResponse response, Object object) {
        String callback = request.getParameter("callback");
        String string = JsonUtils.objectToJson(object);
        if (callback != null && callback.length() > 0) {
            response.setContentType("text/javascript;charset=UTF-8");
            string = (new StringBuilder()).append(callback).append("(").append(string).append(")").toString();
        } else {
            response.setContentType("application/json;charset=UTF-8");
        }
        out(response, string);
    }

    public static void out(HttpServletResponse response, String string) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(string);
        } catch (IOException e) {
            logger.error("AjaxResponseUtil write string error", e);
        } finally {
            if (null != out) {
                out.close();
            }
        }
    }

}
